<template>
  <div v-loading="loading"
       class="login_max_box"
       element-loading-text="正在登录中">
    <div class="form_box">
      <div class="before"
           :class="isTop  ? 'contain-before' : ''">
        <el-form labelWidth="100px"
                 :model="ruleForm"
                 class="demo-ruleForm"
                 statusIcon
                 :rules="rules"
                 style="position:relative">
          <h3>请登录</h3>
          <el-form-item label="用户名"
                        prop="username">
            <el-input v-model="ruleForm.username"
                      type="text"
                      placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码"
                        prop="password">
            <el-input v-model="ruleForm.password"
                      type="password"
                      placeholder="请输入密码"
                      showPassword />
          </el-form-item>
          <el-form-item label="验证码"
                        prop="checkcode">
            <el-input v-model="ruleForm.checkcode"
                      type="text"
                      class="check_code"
                      style="width:40%"
                      placeholder="验证码" />
          </el-form-item>
          <valid-code :value.sync="validCodes"
                      class="checkcode"
                      style="position:absolute" />
        </el-form>
        <el-row>
          <el-button type="primary"
                     class="btn"
                     @click="login()">
            登录
          </el-button>
          <!-- <el-button  @click="submitForm('ruleForm')">提交</el-button> -->
        </el-row>
      </div>
      <div class="after"
           :class="isTop ? 'contain-after' : ''">
        <el-form labelWidth="100px"
                 :model="ruleFormRes"
                 class="demo-ruleForm"
                 statusIcon
                 :rules="rules"
                 style="position: relative">
          <h3>注册</h3>
          <el-form-item label="用户名"
                        prop="username">
            <el-input v-model="ruleFormRes.username"
                      type="text"
                      placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="ruleFormRes.password"
                      type="password"
                      placeholder="请输入密码"
                      showPassword />
          </el-form-item>
          <el-form-item label="确认密码"
                        prop="password2">
            <el-input v-model="ruleFormRes.checkPass"
                      type="password"
                      placeholder="请再次输入密码"
                      showPassword />
          </el-form-item>
        </el-form>
        <el-row>
          <el-button type="success"
                     class="btn"
                     @click="register()">
            注册
          </el-button>
        </el-row>
      </div>
    </div>
    <div class="switch">
      <div class="switch__text">
        <h2>{{ isTop ? '已有账号？' : '没有账号？' }}</h2>
      </div>
      <el-button class="switch__button"
                 type="default"
                 @click.prevent="handleShow">
        <template v-if="isTop">
          👈 去 登 录
        </template>
        <template v-else>
          去 注 册 👉
        </template>
      </el-button>
    </div>
    <star-bg :starNumber="66"
             :w="4"
             :h="4"/>
    <meteor-bg :meteorNumber="6"
               :delay="2"
               :w="2"
               :h="100"
               :rotateDeg="30"/>
  </div>
</template>
<script>
import { Login, Register } from '../api'
import moment from 'moment'
import StarBg from '@/components/starBg.vue'
import MeteorBg from '@/components/meteorBg.vue'

export default {
  components: {
    StarBg,
    MeteorBg
  },
  mounted () {
  },
  data () {
    var checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空'))
      }
      if ((value).toLowerCase() != (this.validCodes).toLowerCase()) {
        callback(new Error('验证码不正确'))
      } else {
        callback()
      }
    }
    var validateName = (rule, value, callback) => {
      var reg = /[a-zA-Z0-9_]{3,15}$/
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入字母开头的合法用户名'))
      }
      callback()
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== this.ruleForm.password) {
        callback(new Error('密码不正确!'))
      } else {
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (this.ruleFormRes.password != this.ruleFormRes.checkPass) {
        callback(new Error('密码不一致'))
      } else {
        callback()
      }
    }

    return {
      loading: false,
      validCodes: '',
      isTop: false,
      ruleForm: {
        username: '',
        password: '',
        checkcode: ''
      },
      ruleFormRes: {
        username: '',
        password: '',
        checkPass: ''
      },
      rules: {
        username: [
          { validator: validateName, trigger: 'blur' }
        ],
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        password2: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        checkcode: [
          { validator: checkCode, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 登录
    async login () {
      this.loading = true
      if ((this.ruleForm.checkcode).toLowerCase() == (this.validCodes).toLowerCase()) {
        await Login({
          userName: this.ruleForm.username,
          userPassword: this.ruleForm.password
        }).then(res => {
          console.log(res)
          const { code, result } = res
          if (code == '200' && result) {
            localStorage.setItem('token', result.userName)
            localStorage.setItem('username', result.userName)
            this.$store.dispatch('setUserInfo', { role: result.userType, username: result.userName })
            this.$router.replace({ name: 'Home' })
            this.loading = false
            this.$message({
              showClose: true,
              message: '登录成功',
              type: 'success'
            })
          } else {
            this.$message({
              showClose: true,
              message: '用户不存在',
              type: 'error'
            })
            this.loading = false
          }
        }).catch(error => {
          console.log(error)
          this.loading = false
          this.$message({
            showClose: true,
            message: '登录失败',
            type: 'error'
          })
          return error
        })
      } else {
        this.loading = false
        this.$message({
          showClose: true,
          message: '登录失败，验证码错误',
          type: 'error'
        })
      }
    },
    // 注册
    register () {
      this.loading = true
      console.log(moment().format('YYYY-MM-DD hh:mm:ss'))
      Register({
        userName: this.ruleFormRes.username,
        userPassword: this.ruleFormRes.password,
        userRegisterTime: moment().format('YYYY-MM-DD hh:mm:ss')
      }).then(res => {
        console.log(res)
        const { code, result, msg } = res
        if (code == '301') {
          this.loading = false
          this.$message({
            showClose: true,
            message: msg,
            type: 'error'
          })
        } else if (code == '200' && result) {
          this.loading = false
          this.$message({
            showClose: true,
            message: '注册成功',
            type: 'success'
          })
          this.isTop = false
        } else {
          this.$message({
            showClose: true,
            message: '注册失败',
            type: 'error'
          })
          this.loading = false
        }
      })
    },
    handleShow () {
      this.isTop = !this.isTop
    }
  }
}
</script>

<style lang="less" scoped>

.login_max_box {
  width: 100%;
  height: 100%;
  background: url(../assets/login-bg.jpg);
  background-size: 100%;
  position: fixed;
}
.form_box {
  width: 400px;
  height: 400px;
  position: relative;
  z-index: 99;
  top: 14%;
  left: 60%;
  perspective: 800px;
  box-sizing: border-box;
}
.form_box .contain-before {
  transform: rotateY(180deg);
}
.form_box .contain-after {
  transform: rotateY(0deg);
}
.before {
  width: 400px;
  height: 400px;
  position: absolute;
  top: 0;
  left: 0;
  // TODO:
  backface-visibility: hidden;
  transition: 1.5s;
  background-color: #fff;
  border-radius: 20px;
  z-index: 3;
}
.after {
  width: 400px;
  height: 400px;
  position: absolute;
  top: 0;
  left: 0;
  transform: rotateY(-180deg);
  transition: 1.5s;
  background-color: #fff;
  border-radius: 20px;
  z-index: 2;
}
h3 {
  text-align: center;
  letter-spacing: 4px;
  font-size: 24px;
  padding: 48px 0 40px;
}
.checkcode {
  width: 80px;
  height: 40px;
  position: absolute;
  z-index: 99;
  right: 60px;
  bottom: 0;
}
.btn {
  width: 64%;
  margin-left: 18%;
}
.el-input {
  width: 80%;
}

.switch {
  width: 400px;
  height: 100px;
  position: absolute;
  z-index: 2021;
  background-color: #fff;
  border-radius: 20px;
  position: absolute;
  bottom: 14%;
  left: 60%;
  opacity: 0.88;
  display: flex;
  justify-content: center;
  align-items: center;
  &__text {
    text-align: center;
  }
  &__button {
    width: 100px;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

</style>
